﻿import { TokenManager, ServiceConfig, route, Identity, Response } from "../common";
import { WebException } from "./webException";
import { AuthService } from '../service/authService';
var webconfig = require("../../webconfig").webconfig;

export class AuthenticationController {
    private authSvr: AuthService;
    constructor() {
        this.authSvr = ServiceConfig.Current.GetService<AuthService>("authService");
    }

    toString(){
        return "AuthenticationController";
    }

    /**
     * 店员登录
     */
    @route({ method: 'post', path: '/api/auth/login' })
    async login(ctx, next) {
        let store_emp = ctx.request.body;

        if (!store_emp.storeId) throw new WebException("店铺ID不能为空！");
        if (!store_emp.account) throw new WebException("账户不能为空！");
        if (!store_emp.password) throw new WebException("密码不能为空！");

        let res: any = {};
        if (store_emp.storeId != webconfig.storeId) throw new WebException("该店铺不存在此员工！");
        let token = TokenManager.Current.GetTokenByAccount(store_emp.account);
        if (token) {
            if (token.Identity.password != store_emp.password) throw new WebException("密码错误！");
            //如果已经存在token 直接获取
            res.employee = {
                employeeNumber: token.Identity.userName,
                joinTime: token.Identity.joinTime,
                userId: token.Identity.userId,
                userName: token.Identity.userName
            };
            res.token = token.TokenValue;
        }
        else {
            let result = await this.authSvr.login(store_emp.storeId, store_emp.account, store_emp.password);
            res.employee = {
                userName: (<any>result.employee).user.name,
                joinTime: result.employee.joinTime,
                userId: result.employee.id,
                password: store_emp.password
            };
            TokenManager.Current.AddToken(res.employee, result.token);
            //登录成功写入到token管理器
            res.token = result.token;
        }

        //返回值中删除密码
        delete res.password;
        ctx.response.body = Response.ok("登录成功", res);

        await next();
    }
}